<?php
namespace app\admin\controller;

//应用市场信息管理
class Market extends Auth
{

    //公共模块，无需权限检测
    protected $public_action = array('goodsedit','gstate','gdel','gsort','gcatedit','gcatstate','gcatdel','gcatsort','ordersend','ordereditflow','ordercancel','agree');


    //商品管理
    //*+------------------------------------------------------------------------+*/


    /*
     *应用商品列表
     *@author leiqianyong 2020-10-12 9:50 AM
     */
    public function goods(){
        $map[]=['hide_flag','=',0];

        //按商品名，关键词查询
        $keywords=input('keywords','','trim');
        if($keywords)$map[] = ['name','like', '%'.$keywords.'%'];
        $this->assign('keywords',$keywords);

        //状态
        $state=input('state',1);
        if($state>-1)$map[]=['state','=',$state];
        $this->assign('state',$state);

        //商品id
        $id=input('id');
        if($id)$map[]=['id','=',$id];
        $this->assign('id',$id);

        //商品类型
        $cat=input('cat',0);
        if($cat)$map[]=['cat','=',$cat];
        $this->assign('cat',$cat);

        //时间段
        $map = $this->condtime($map);

        $pagesize=20;
        $sort_str='sort desc,id desc';
        $list = db("isgoods")->where($map)->order($sort_str)->paginate($pagesize,false,['query'=>request()->param()]);

        $this->assign('list',$list);

        //分类信息
        $this->grtn();

        $reviewary=array(-1=>'全部',1=>'上架',0=>'下架');
        $this->assign('reviewary',$reviewary);

        return $this->fetch();
    }


    /*
    * 添加修改商品信息
    * @author leiqianyong 2020-10-12 10:06 AM
    */
    public function goodsedit(){
        $id = input('id',0) ;

        if(request()->isPost() || request()->isAjax()){
            $data=request()->post();
            $result = $this->validate($data ,'app\admin\validate\Isgoods');
            if($result !== true)$this->error($result);

            $album_data=$this->album_config();
            $data=array_merge($data,$album_data);

            //规格组合
            $attr_groups=input('attr_groups','','trim');
            $data['attr_groups']=htmlspecialchars_decode($attr_groups);
            //规格商品组合
            $val_groups=input('val_groups','','trim');
            $groups=$data['val_groups']=htmlspecialchars_decode($val_groups);

            //最大和最小价格
            if($groups){
                $max=0; //最大
                $min=1000000; //最小
                $groups_rtn=json_decode($groups,true);
                foreach($groups_rtn as $vo){
                   if($vo['price'] && $vo['price']>$max)$max=$vo['price'];
                   if($vo['price'] && $vo['price']<$min)$min=$vo['price'];
                }

                $data['price_max']=$max;
                $data['price_min']=$min;
            }

            $object=db('isgoods');

            $url = request()->action();

            //修改操作
            if($id){
                $data['time_update']=time();
                $res=$object->strict(false)->where(['id'=>$id])->update($data);
                if(false===$res)$this->error('修改失败');
                $this->groups_goods($id,$groups,$attr_groups);
                return $this->success("修改成功",url($url));
            }

            //添加操作
            $data['time']=$data['time_update']=time();
            $id = $object->strict(false)->insertGetId($data);
            if(!$id)$this->error("添加失败");
            $this->groups_goods($id,$groups,$attr_groups);
            return $this->success("添加成功",url($url,'id='.$id),['cmd'=>1]);
            //$this->editDataMethod($data,'isgoods');
        }


        if($id){
            $map['id']=$id;
            $info = db('isgoods')->where($map)->find();
            $this->assign ('info',$info);

            //获取商品规格数据
            $ggmap[]=['goods_id','=',$id];
            $ggmap[]=['is_delete','=',0];
            $glist=db('isgoods_attr')->where($ggmap)->field('sign_id ids,sign_str names,stock,price,no,weight,img')->select();
            if($glist)$this->assign('var_groups',json_encode($glist));
        }

        //分类信息
        $this->grtn();

        return $this->fetch();
    }


    /**
     * 添加修改规格商品数据
     * @param $gid   对应商品id
     * @param $goods 商品数据json
     * @param $groups 商品规格数组
     * @return bool|void
     */
    private function groups_goods($gid,$goods,$groups){
        if(!$gid)return false;
        if(!$goods){
            //标记删除其他数据
            $object=db('isgoods_attr');
            $data['is_delete']=0;
            $map[]=['goods_id','=',$gid];
            $map[]=['sign_id','neq',$gid];
            $object->where($map)->update($data);

            //查询是否有唯一数据
            $umap[]=['sign_id','=',$gid];
            $umap[]=['is_delete','=',0];
            $oinfo=$object->where($umap)->find();

            $stock=input('num_store',1000);
            $ndata['stock']=$stock?$stock:10000;
            $ndata['price']=input('price_act',0);
            $ndata['img']=input('coverimg');
            //修改
            if($oinfo){
                $object->where($umap)->update($ndata);
                return;
            }

            $ndata['sign_id']=$ndata['goods_id']=$gid;
            $object->insertGetId($ndata);
            return;
        }

        //规格商品数组
        $gtn=json_decode($goods,true);
        $ary=parseRtn($gtn,'ids');

        //规格类型
        $attr_rtn=json_decode($groups,true);

        $object= db('isgoods_attr');
        $map[]=['goods_id','=',$gid];
        $map[]=['is_delete','=',0];
        $glist=$object->where($map)->select();
        //删除去除的，更新已有的，组合待添加的
        $ary_edited=[]; //记录已修改的数据
        if($glist){
            $ary_del=[]; //需要删除的
            foreach($glist as $vo){
                $item=$ary[$vo['sign_id']];
                //存在则修改
                if($item){
                    $data['stock']=$item['stock'];
                    $data['price']=$item['price'];
                    $data['weight']=$item['weight'];
                    $data['sign_str']=$item['names'];
                    $data['no']=$item['no'];
                    $data['img']=$item['img'];
                    $data['groups']=$this->createGroups($vo['sign_id'],$attr_rtn);
                    $imap['goods_id']=$gid;
                    $imap['sign_id']=$vo['sign_id'];
                    $object->removeOption('where')->where($imap)->update($data);
                    $ary_edited[]=$vo['sign_id'];
                    continue;
                }

                $ary_del[]=$vo['sign_id'];
            }

            //删除已没有的商品
            if($ary_del) {
                $dmap[] =['goods_id','=',$gid];
                $dmap[] =['sign_id','in',$ary_del];
                $ddata['is_delete']=1;
                $object->where($dmap)->update($ddata);
            }
        }

        //移除已修改的数据
        $grtn=[];
        foreach($ary as $key=>$vo){
            if(in_array($key,$ary_edited))continue;
            $vdata['goods_id']=$gid;
            $vdata['sign_id']=$vo['ids'];
            $vadata['groups']=$this->createGroups($vo['ids'],$attr_rtn);
            $vdata['stock']=$vo['stock'];
            $vdata['price']=$vo['price'];
            $vdata['weight']=$vo['weight'];
            $vdata['no']=$vo['no'];
            $vdata['img']=$vo['img'];
            $vdata['sign_str']=$vo['names'];
            $grtn[]=$vdata;
        }


        if(count($grtn)>0)$object->insertAll($grtn);
    }

    //创建商品分组
    public function createGroups($ids,$groups){
        if(!$ids)return;
        $rtn=explode(';',$ids);
        foreach($rtn as $key=>$vo){
            $ary[]=['name'=>$groups[$key]['skuTypeTitle'],'val'=>$groups[$key]['skuValues'][$vo]['skuValueTitle']];
        }

        return json_encode($ary);
    }

    //修改商品的上架下架状态
    public function gstate(){
        $this->state('isgoods');
    }


    //删除商品信息
    public function gdel(){
        $this->del('isgoods');
    }


    //排序功能
    public function gsort(){
        $this->sort('isgoods');
    }


    //图册数据设置
    public function album_config(){
        $files_alt=input('files_alt');
        $files_url=input('files_url');
        if(empty($files_url))$this->error('请上传图片');
        $data['coverimg']=$coverimg=input('coverimg');
        $ary=array();
        if($files_url){
            foreach($files_url as $k=>$v){
                $ary[]=array('url'=>$v,'alt'=>$files_alt[$k]);
            }
            $data['album']=var_export($ary,true);
            if(empty($coverimg)){
                $data['coverimg']=$files_url[0];
            }
        }else{
            $data['coverimg']='';
        }

        return $data;
    }


    //应用商品分类
    public function gcatindex(){
        $keywords=input('keywords','','trim');
        if($keywords)$map[]=['name','like','%'.$keywords.'%'];
        $this->assign('keywords',$keywords);

        $state=input('state',-1);
        if($state>-1)$map[]=['state','=',$state];
        $this->assign('state',$state);

        $pagesize=20;
        $sort_str="sort desc";
        $list = db("isgoodscat")->where($map)->order($sort_str)->paginate($pagesize,false,['query'=>request()->param()]);
        $this->assign('list',$list);

        //状态
        $reviewary=array(-1=>'全部',1=>'启用',0=>'禁用');
        $this->assign('reviewary',$reviewary);

        return $this->fetch();
    }


    //编辑页面信息
    public function gcatedit(){

        if(request()->isAJAX()){
            $name=input('name','','trim');
            if(!$name)$this->error('请输入名称');
            $info=input('info','','trim');

            $data['name']=$name;
            $data['info']=$info;

            $this->editDataMethod($data,'isgoodscat');
        }

        $id=input('id');
        if($id){
            $map[]=['id','=',$id];
            $info=db('isgoodscat')->where($map)->find();
            $this->assign('info',$info);
        }

        return $this->fetch();
    }


    //状态修改
    public function gcatstate(){
        $this->state('isgoodscat');
    }


    //删除类型
    public function gcatdel(){
        $this->delete('isgoodscat');
    }


    //排序设置
    public function gcatsort(){
        $this->sort('isgoodscat');
    }


    //获取分类信息
    public function grtn(){
        $map['state']=1;
        $order='sort desc';
        $rtn=db('isgoodscat')->field('id,name')->where($map)->order($order)->select();
        $this->assign('gcat',parseRtn($rtn,'id'));
    }


    //订单管理
    //*+------------------------------------------------------------------------+*/


    //订单列表
    public function order(){
        //订单状态
        $state=input('state',-1);
        if($state>-1)$map[]=['state_pay','=',$state];
        $this->assign('state',$state);

        //订单编号
        $sn=input('sn','','trim');
        if($sn)$map[]=['order_sn','like','%'.$sn.'%'];

        //商品名称
        $keywords=input('keywords','','trim');
        if($keywords)$map[]=['gname','like','%'.$keywords.'%'];

        //时间段
        $time=input('time');
        $map = $this->condtime($map,$time);

        $pagesize=20;
        $sort_str='id desc';
        $res = db("isorder")->where($map)->order($sort_str)->paginate($pagesize,false,['query'=>request()->param()]);
        $list = $res->toArray()['data'];

        //获取会员信息
        if($list){
            $uid=parseArray($list,'uid');
            $umap[]=['id','in',$uid];
            $ulist=db('user')->where($umap)->column('id,account');
            $this->assign('urtn',$ulist);
        }

        //支付状态
        $reviewary=[-1=>'全部',0=>'待支付',1=>'已支付'];

        return view("",compact('state','keywords','res','list','reviewary','sn','time'));
    }


    //订单发货
    public function ordersend(){
        $id=input('id');
        if(!$id)return false;
        $object=M('isorder');
        $map['id']=$id;

        if(IS_AJAX || IS_POST){
            //发货方式
            $ecat=input('ecat',1);
            $ecom=input('ecom','','trim');
            $ecode=input('ecode','',trim);
            if(1==$ecat && !$ecom)$this->error('请输入快递公司');
            if(1==$ecat && !$ecode)$this->error('请输入快递单号');
            $data['ecat']=$ecat;
            $data['ecom']=$ecom;
            $data['ecode']=$ecode;
            $data['time_ecom']=NOW_TIME;
            $data['state']=2;

            $res=$object->where($map)->save($data);
            if(false===$res)$this->error('发货失败');
            $this->success('发货成功');
            return;
        }

        $oinfo=$object->where($map)->find();
        $this->assign('oinfo',$oinfo);

        $this->display();
    }


    //修改发货信息
    public function ordereditflow(){
        $id=input('id');
        if(!$id)return false;
        $object=M('isorder');
        $map['id']=$id;

        if(IS_AJAX || IS_POST){
            //发货方式
            $ecat=input('ecat',1);
            $ecom=input('ecom','','trim');
            $ecode=input('ecode','',trim);
            if(1==$ecat && !$ecom)$this->error('请输入快递公司');
            if(1==$ecat && !$ecode)$this->error('请输入快递单号');
            $data['ecat']=$ecat;
            $data['ecom']=$ecom;
            $data['ecode']=$ecode;

            $res=$object->where($map)->save($data);
            if(false===$res)$this->error('修改失败');
            $this->success('修改成功');
            return;
        }

        $oinfo=$object->where($map)->find();
        $this->assign('oinfo',$oinfo);

        $this->display();
    }


    //订单退货
    public function ordercancel(){
        $id=input('id');
        if(!$id)return false;
        $object=M('isorder');
        $map['id']=$id;

        if(IS_AJAX || IS_POST){
            $reinfo=input('reinfo','','trim');
            if(!$reinfo)$this->error('请输入退货原因');
            $data['reinfo']=$reinfo;
            $data['reback']=input('reback',1);
            $data['state']=4;

            $res=$object->where($map)->save($data);
            if(false===$res)$this->error('退货失败');

            $reback=input('reback',1);
            if(1==$reback){
                //应用变更，应用日志
                $ginfo=$object->where($map)->find();
                $jfsum=$ginfo['sum'];
                $jfdata['uid']=$ginfo['uid'];
                $jfdata['type']=1;
                $jfdata['time']=NOW_TIME;
                $jfdata['comment']='应用兑换退货返还应用：'.$jfsum;
                $jfdata['num']=$jfsum;
                $jfdata['mid']=$id;
                M('user')->where($umap)->setInc('integal',$jfsum);
                M('uscore')->add($jfdata);
            }

            $this->success('退货成功');
            return;
        }

        $oinfo=$object->where($map)->find();
        if(3==$oinfo['state'])exit('订单已完成不能退货');
        $this->assign('oinfo',$oinfo);

        $this->display();
    }


    //确认会员已收货，结束订单
    public function agree(){
        $oid=input('oid');
        $umap['id']=$oid;
        $umap['state']=2;

        $data['state']=3;
        if(false===M('isorder')->where($umap)->save($data))$this->error('确认失败');
        $this->success('确认成功');
    }



}
